<template>
  <view class="address-select-container">
    <!-- 顶部导航栏 -->
    <view class="header">
      <view class="back-btn" @click="goBack" @touchstart="onTouchStart" @touchend="onTouchEnd">
        <text class="back-icon">‹</text>
      </view>
      <view class="header-title">选择配送地址</view>
      <view class="add-btn" @click="addNewAddress">
        <text class="add-icon">+</text>
      </view>
    </view>

    <!-- 地址列表 -->
    <view class="address-list">
      <!-- 空状态 -->
      <view v-if="addressList.length === 0" class="empty-container">
        <text class="empty-text">暂无地址，请添加</text>
        <button class="add-address-btn" @click="addNewAddress">
          <text class="btn-text">添加地址</text>
        </button>
      </view>
      
      <!-- 地址列表 -->
      <view 
        v-else
        v-for="(address, index) in addressList" 
        :key="address.id"
        :class="['address-item', { active: selectedIndex === index }]"
        @click="selectAddress(index)"
      >
        <view class="address-info">
          <view class="address-header">
            <text class="contact-name">{{ address.name }}</text>
            <text class="contact-phone">{{ address.phone }}</text>
            <view v-if="address.isDefault" class="default-tag">默认</view>
          </view>
          <view class="address-detail">
            <text class="address-text">{{ address.fullAddress }}</text>
          </view>
        </view>
        <view class="address-actions">
          <view class="edit-btn" @click.stop="editAddress(index)">
            <text class="edit-icon">✏️</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部确认按钮 -->
    <view class="bottom-actions" v-if="selectedIndex !== -1">
      <button class="confirm-btn" @click="confirmAddress">
        <text class="confirm-text">确认选择</text>
      </button>
    </view>
    
    <!-- 紧急返回按钮 -->
    <view class="emergency-back">
      <button class="emergency-back-btn" @click="emergencyBack">
        <text class="emergency-back-text">返回上一页</text>
      </button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { getAddressList } from '@/api/express-pickup'
import type { AddressInfo } from '@/types/api/express-pickup'

// 响应式数据
const selectedIndex = ref(-1)
const addressList = ref<AddressInfo[]>([])

// 获取地址列表
const fetchAddressList = async () => {
  try {
    const response = await getAddressList()
    
    if (response.success) {
      addressList.value = response.data
      // 选择默认地址
      const defaultIndex = addressList.value.findIndex(addr => addr.isDefault)
      if (defaultIndex !== -1) {
        selectedIndex.value = defaultIndex
      }
    } else {
      uni.showToast({
        title: response.message || '获取地址失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('获取地址列表失败:', error)
    uni.showToast({
      title: '网络错误，请重试',
      icon: 'none'
    })
  }
}

// 页面加载时获取地址列表
onMounted(() => {
  fetchAddressList()
})

// 方法
const goBack = () => {
  console.log('返回按钮被点击')
  try {
    uni.navigateBack({
      success: () => {
        console.log('返回成功')
      },
      fail: (err) => {
        console.error('返回失败:', err)
        // 如果返回失败，尝试跳转到首页
        uni.switchTab({
          url: '/pages/main/main'
        })
      }
    })
  } catch (error) {
    console.error('返回出错:', error)
    // 出错时跳转到首页
    uni.switchTab({
      url: '/pages/main/main'
    })
  }
}

const selectAddress = (index: number) => {
  selectedIndex.value = index
}

const addNewAddress = () => {
  uni.navigateTo({
    url: '/pages/address-add/address-add'
  })
}

const editAddress = (index: number) => {
  const address = addressList.value[index]
  uni.navigateTo({
    url: '/pages/address-add/address-add',
    success: (res) => {
      // 传递地址数据到编辑页面
      res.eventChannel.emit('editAddress', address)
    }
  })
}

const confirmAddress = () => {
  if (selectedIndex.value === -1) {
    uni.showToast({
      title: '请选择一个地址',
      icon: 'none'
    })
    return
  }

  const selectedAddress = addressList.value[selectedIndex.value]
  
  // 使用事件总线返回选中的地址
  uni.$emit('addressSelected', selectedAddress.fullAddress)
  
  // 或者使用页面参数传递
  const eventChannel = getOpenerEventChannel()
  eventChannel.emit('addressSelected', selectedAddress.fullAddress)
  
  uni.navigateBack()
}

// 触摸事件处理
const onTouchStart = () => {
  console.log('触摸开始')
}

const onTouchEnd = () => {
  console.log('触摸结束')
  // 触摸结束后也尝试返回
  goBack()
}

// 紧急返回方法
const emergencyBack = () => {
  console.log('紧急返回被点击')
  try {
    // 尝试多种返回方式
    uni.navigateBack({
      delta: 1,
      success: () => {
        console.log('紧急返回成功')
      },
      fail: () => {
        // 如果返回失败，跳转到首页
        uni.switchTab({
          url: '/pages/main/main'
        })
      }
    })
  } catch (error) {
    console.error('紧急返回出错:', error)
    uni.switchTab({
      url: '/pages/main/main'
    })
  }
}
</script>

<style scoped>
.address-select-container {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 120rpx;
}

/* 顶部导航栏 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
}

.back-btn {
  width: 80rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  border-radius: 50%;
  transition: all 0.3s ease;
  cursor: pointer;
}

.back-btn:active {
  background-color: #e0e0e0;
  transform: scale(0.95);
}

.back-icon {
  font-size: 44rpx;
  color: #333;
  font-weight: bold;
}

.header-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.add-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.add-icon {
  font-size: 32rpx;
  color: #f44336;
  font-weight: bold;
}

/* 地址列表 */
.address-list {
  padding: 20rpx;
}

.address-item {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border: 2rpx solid transparent;
  transition: all 0.3s ease;
}

.address-item.active {
  border-color: #f44336;
  background-color: #fff5f5;
}

.address-info {
  flex: 1;
}

.address-header {
  display: flex;
  align-items: center;
  gap: 20rpx;
  margin-bottom: 15rpx;
}

.contact-name {
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
}

.contact-phone {
  font-size: 28rpx;
  color: #666;
}

.default-tag {
  background-color: #f44336;
  color: #fff;
  font-size: 22rpx;
  padding: 4rpx 12rpx;
  border-radius: 12rpx;
}

.address-detail {
  margin-bottom: 10rpx;
}

.address-text {
  font-size: 28rpx;
  color: #333;
  line-height: 1.4;
}

.address-actions {
  display: flex;
  align-items: center;
}

.edit-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.edit-icon {
  font-size: 28rpx;
}

/* 底部按钮 */
.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx;
  background-color: #fff;
  border-top: 1rpx solid #eee;
}

.confirm-btn {
  width: 100%;
  height: 88rpx;
  background-color: #f44336;
  color: #fff;
  border: none;
  border-radius: 10rpx;
  font-size: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.confirm-text {
  font-size: 32rpx;
  font-weight: 500;
}

/* 紧急返回按钮 */
.emergency-back {
  position: fixed;
  top: 120rpx;
  right: 20rpx;
  z-index: 1000;
}

.emergency-back-btn {
  background-color: #ff9800;
  color: #fff;
  border: none;
  border-radius: 25rpx;
  padding: 15rpx 25rpx;
  font-size: 24rpx;
  box-shadow: 0 4rpx 12rpx rgba(255, 152, 0, 0.3);
}

.emergency-back-btn:active {
  transform: scale(0.95);
}
</style>
